package com.bonc.ioc.demo.base.controller;


import com.alibaba.fastjson.JSON;
import com.bonc.ioc.common.util.JsonToolsUtil;
import com.bonc.ioc.demo.base.page.PageData;
import com.bonc.ioc.demo.base.page.PageResult;
import com.bonc.ioc.demo.constant.DepartmentInfo;
import com.bonc.ioc.demo.constant.UserInfo;
import com.bonc.ioc.demo.exception.McpException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * @author fengshuonan
 * @Date 2017年1月22日 下午11:06:41
 */
@Slf4j
public abstract class BaseController {

    protected String id;
    protected String ids;
    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected HttpSession session;
    protected PageResult pageResult;
    private StringRedisTemplate redisTemplate;

    @ModelAttribute
    public void setReqAndRes(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
        this.session = request.getSession();
        if (redisTemplate == null) {
            BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
            redisTemplate = (StringRedisTemplate) factory.getBean("stringRedisTemplate");
        }
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }


    /**
     * 得到PageData
     */
    public PageData getPageData() {
        return new PageData(request);
    }

    /**
     * 得到ModelAndView
     */
    public ModelAndView getModelAndView() {
        return new ModelAndView();
    }


    /**
     * 获取登录用户的IP
     *
     * @throws Exception
     */
    public String getRemoteIp() throws Exception {
        String ip = "";
        String key = "x-forwarded-for";
        if (request.getHeader(key) == null) {
            ip = request.getRemoteAddr();
        } else {
            ip = request.getHeader(key);
        }
        return ip;
    }


    /**
     * 客户端返回JSON字符串
     *
     * @param response
     * @param object
     * @return
     */
    protected String renderString(HttpServletResponse response, Object object) {
        return renderString(response, JsonToolsUtil.toJsonString(object), "application/json");
    }

    /**
     * 客户端返回字符串
     *
     * @param response
     * @param string
     * @return
     */
    protected String renderString(HttpServletResponse response, String string, String type) {
        try {
            response.reset();
            response.setContentType(type);
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(string);
            return null;
        } catch (IOException e) {
            return null;
        }
    }


    /**
     * 获取用户
     *
     * @return
     */
    protected UserInfo getUser() {
        return getUserByTokenId();
    }

    /**
     * * @description 根据tokenid返回用户
     *
     * @return: UserInfo 用户信息
     * @since: 1.0.0
     * @Author: jin.xu
     * @Date: 12/10/20 10:14 AM
     * @change: 12/10/20 10:14 AM by jin.xu for init
     */
    private UserInfo getUserByTokenId() {
        String tokenId = request.getHeader("tokenId");
        if (tokenId == null) {
            throw new McpException("当前用户未登录");
        }
        String user = redisTemplate.opsForValue().get(tokenId);
        if (StringUtils.isEmpty(user)) {
            throw new McpException("当前用户未登录");
        }
        log.info("user = {}", user);
        return JSON.parseObject(new String(Base64.decodeBase64(user)), UserInfo.class);
    }

    /**
     * * @description 获取当前用户对应的部门
     *
     * @return: DepartmentInfo 部门信息
     * @since: 1.0.0
     * @Author: jin.xu
     * @Date: 12/10/20 10:15 AM
     * @change: 12/10/20 10:15 AM by jin.xu for init
     */
    protected DepartmentInfo getDepartment() {
        UserInfo userInfo = getUserByTokenId();

        // 先获取用户对应的部门信息 此处存放的是用户对应的当前部门信息 通过MCP-SYS服务写入redis
        String userKey = "mcp-sys-server:department:user:" + userInfo.getId();
        String departmentId = redisTemplate.opsForValue().get(userKey);

        // 通过id找到部门信息
        if (StringUtils.isEmpty(departmentId)) {
            // 用户没有对应到部门
            return null;
        }

        departmentId = departmentId.replace("\"", "");

        String departmentKey = "mcp-sys-server:department:departmentInfo:" + departmentId;
        String departmentJson = redisTemplate.opsForValue().get(departmentKey);
        log.info("department = {}", departmentJson);

        return JSON.parseObject(new String(Base64.decodeBase64(departmentJson)), DepartmentInfo.class);
    }

    /**
     * * @description 获取请求服务名
     *
     * @return: null
     * @since: 1.0.0
     * @Author: jin.xu
     * @Date: 12/14/20 4:14 PM
     * @change: 12/14/20 4:14 PM by jin.xu for init
     */
    protected String getRequestServiceName() {
        String requestServiceName = request.getHeader("requestServiceName");

        if (StringUtils.isEmpty(requestServiceName)) {
            requestServiceName = "null";
        }

        return requestServiceName;
    }
}